<?php
/**
 * 销售机会控制器
 */

namespace app\controller\customer;

use app\BaseController;
use app\model\customer\CustomerChance as CustomerChanceModel;
use app\model\admin\User as UserModel; // 引入User模型
use think\facade\Db;
use think\facade\Cache;

class Chance extends BaseController
{
    /**
     * 查看销售机会列表
     */
    public function list()
    {
        $cid = input('cid');
        $customer_id = input('customer_id');
        $stage = input('stage');
        $keywords = input('keywords');
        $page = input('page', 1);
        $limit = input('limit', 10);
        
        try {
            // 使用直接查询而不是使用关联，避免潜在的错误，并关联客户表获取客户名称
            // 同时联查阶段文字数据
            $query = Db::name('customer_chance')
                ->alias('cc')
                ->leftJoin('admin u', 'cc.admin_id = u.id')
                ->leftJoin('customer c', 'cc.customer_id = c.id')
                ->field('cc.*, u.username, u.nickname, c.name as customer_name');
                
            // 优先使用customer_id参数，如果没有再使用cid参数
            if ($customer_id) {
                $query->where('cc.customer_id', '=', $customer_id);
            } elseif ($cid) {
                $query->where('cc.customer_id', '=', $cid);
            }
            
            // 如果提供了阶段参数
            if ($stage !== '' && $stage !== null) {
                $query->where('cc.stage', '=', $stage);
            }
            
            // 如果提供了关键词，同时对机会名称和客户名称进行模糊搜索
            if ($keywords) {
                $query->where('cc.title|c.name', 'like', '%' . $keywords . '%');
            }
            
            // 添加条件：只查询未删除的记录
            $query->where('cc.delete_time', '=', 0);
                
            $query->order('cc.create_time', 'desc');
                
            // 获取总数
            $total = $query->count();
            
            // 分页查询
            $list = $query->page($page, $limit)->select()->toArray();
            
            // 获取阶段映射关系（从数据库获取）
            $stageMap = $this->getStageMap();
            
            // 处理数据
            foreach ($list as &$item) {
                // 处理管理员名称
                $item['admin_name'] = $item['nickname'] ?: $item['username'];
                unset($item['nickname'], $item['username']);
                
                // 确保时间字段是整数
                if (isset($item['create_time']) && $item['create_time']) {
                    $item['create_time'] = (int)$item['create_time'];
                }
                
                // 确保发现时间和预期时间是整数
                if (isset($item['discovery_time']) && $item['discovery_time']) {
                    $item['discovery_time'] = (int)$item['discovery_time'];
                }
                
                if (isset($item['expected_time']) && $item['expected_time']) {
                    $item['expected_time'] = (int)$item['expected_time'];
                }
                
                // 添加阶段文字数据
                if (isset($item['stage']) && isset($stageMap[$item['stage']])) {
                    $item['stage_text'] = $stageMap[$item['stage']]['title'];
                } else {
                    $item['stage_text'] = '未知';
                }
            }
            
            return $this->paginate($list, $total, $page, $limit, '获取销售机会列表成功');
        } catch (\Exception $e) {
            // 记录详细的错误信息到日志
            \think\facade\Log::error('获取销售机会列表失败: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取销售阶段映射关系
     * 从oa_basic_customer表中获取types=4的数据，并做缓存处理
     */
    private function getStageMap()
    {
        // 尝试从缓存中获取数据
        $cacheKey = 'customer_chance_stage_map';
        $stageMap = Cache::get($cacheKey);
        
        if (!$stageMap) {
            // 缓存中没有数据，从数据库查询
            try {
                $stages = Db::name('basic_customer')
                    ->where('types', 4)  // types=4表示销售阶段
                    ->where('status', 1) // 只获取启用状态的数据
                    ->field('id, title')
                    ->order('id', 'asc')
                    ->select()
                    ->toArray();
                
                // 构建阶段映射关系
                $stageMap = [];
                foreach ($stages as $stage) {
                    $stageMap[$stage['id']] = [
                        'id' => $stage['id'],
                        'title' => $stage['title']
                    ];
                }
                
                // 将数据缓存30分钟
                Cache::set($cacheKey, $stageMap, 1800);
            } catch (\Exception $e) {
                // 如果查询失败，使用默认的硬编码数据作为后备方案
                \think\facade\Log::error('获取销售阶段数据失败: ' . $e->getMessage());
                $stageMap = [
                    1 => ['id' => 1, 'title' => '初步接触'],
                    2 => ['id' => 2, 'title' => '需求分析'],
                    3 => ['id' => 3, 'title' => '方案报价'],
                    4 => ['id' => 4, 'title' => '商务谈判'],
                    5 => ['id' => 5, 'title' => '成交'],
                    6 => ['id' => 6, 'title' => '失败']
                ];
            }
        }
        
        return $stageMap;
    }
    
    /**
     * 获取销售阶段选项（用于前端下拉选择）
     */
    public function stageOptions()
    {
        try {
            $stageMap = $this->getStageMap();
            $options = [];
            
            foreach ($stageMap as $id => $stage) {
                $options[] = [
                    'id' => $id,
                    'title' => $stage['title']
                ];
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $options
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 查看单个销售机会
     */
    public function view()
    {
        $id = input('id');
        if (!$id) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }
        
        // 关联查询User模型获取管理员名称
        $chance = CustomerChanceModel::with(['admin' => function($query) {
            $query->field('id,username,nickname');
        }])->find($id);
        
        if (!$chance) {
            return json(['code' => 1, 'msg' => '记录不存在']);
        }
        
        // 添加admin_name字段
        if (isset($chance['admin'])) {
            $chance['admin_name'] = $chance['admin']['nickname'] ?: $chance['admin']['username'];
            unset($chance['admin']); // 移除admin对象
        } else {
            $chance['admin_name'] = '';
        }
        
        // 获取阶段映射关系
        $stageMap = $this->getStageMap();
        
        // 添加阶段文字数据
        if (isset($chance['stage']) && isset($stageMap[$chance['stage']])) {
            $chance['stage_text'] = $stageMap[$chance['stage']]['title'];
        } else {
            $chance['stage_text'] = '未知';
        }
        
        return json(['code' => 0, 'msg' => 'success', 'data' => $chance]);
    }
    
    /**
     * 新建销售机会
     */
    public function add()
    {
        $data = input('post.');
        $data['admin_id'] = $this->getUserId();
        $data['create_time'] = time();
        
        // 确保时间字段是整数
        if (isset($data['discovery_time'])) {
            $data['discovery_time'] = (int)$data['discovery_time'];
        } else {
            $data['discovery_time'] = 0;
        }
        
        if (isset($data['expected_time'])) {
            $data['expected_time'] = (int)$data['expected_time'];
        } else {
            $data['expected_time'] = 0;
        }
        
        try {
            $result = CustomerChanceModel::create($data);
            if ($result) {
                return json(['code' => 0, 'msg' => '添加成功', 'data' => ['id' => $result->id]]);
            } else {
                return json(['code' => 1, 'msg' => '添加失败', 'data' => []]);
            }
        } catch (\Exception $e) {
            return json(['code' => 10501, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }
    
    /**
     * 编辑销售机会
     */
    public function edit()
    {
        $id = input('id');
        if (!$id) {
            return json(['code' => 1, 'msg' => '参数错误', 'data' => []]);
        }
        
        $data = input('post.');
        $data['update_time'] = time();
        
        // 确保时间字段是整数
        if (isset($data['discovery_time'])) {
            $data['discovery_time'] = (int)$data['discovery_time'];
        } else {
            $data['discovery_time'] = 0;
        }
        
        if (isset($data['expected_time'])) {
            $data['expected_time'] = (int)$data['expected_time'];
        } else {
            $data['expected_time'] = 0;
        }
        
        try {
            $result = CustomerChanceModel::where('id', $id)->update($data);
            if ($result) {
                return json(['code' => 0, 'msg' => '编辑成功', 'data' => ['id' => $id]]);
            } else {
                return json(['code' => 1, 'msg' => '编辑失败', 'data' => []]);
            }
        } catch (\Exception $e) {
            return json(['code' => 10501, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }
    
    /**
     * 删除销售机会（软删除）
     */
    public function del()
    {
        $id = input('id');
        if (!$id) {
            return json(['code' => 1, 'msg' => '参数错误', 'data' => []]);
        }
        
        $result = CustomerChanceModel::where('id', $id)->update(['delete_time' => time()]);
        if ($result) {
            return json(['code' => 0, 'msg' => '删除成功', 'data' => ['id' => $id]]);
        } else {
            return json(['code' => 1, 'msg' => '删除失败', 'data' => []]);
        }
    }
}
